package com.finance.rule.controller;

import com.finance.base.constant.BaseConstants;
import com.finance.base.enums.CalculateTypeEnum;
import com.finance.base.enums.TargetEnum;
import com.finance.base.exception.BaseException;
import com.finance.framework.controller.BaseController;
import com.finance.framework.controller.Result;
import com.finance.framework.file.FileUtils;
import com.finance.rule.bean.pojo.*;
import com.finance.rule.export.*;

import com.finance.rule.bean.pojo.NewRuleList;
import com.finance.rule.bean.pojo.NewWeightRule;
import com.finance.rule.export.NewWeightRuleImportTemplateBean;
import com.finance.rule.export.NewWeightRuleParse;

import com.finance.rule.request.NewPieceRuleImportReq;
import com.finance.rule.request.NewRulesReq;
import com.finance.rule.request.NewWeightRuleImportReq;
import com.finance.rule.service.INewRuleService;
import com.finance.rule.service.ISettingLogService;
import com.finance.rule.service.ISettlementRegionService;
import com.finance.system.bean.pojo.*;
import com.finance.system.service.ICarrierService;
import com.finance.system.service.IRegionCodeService;
import com.finance.system.service.ISupplierService;
import com.finance.util.export.ExportBuilder;
import com.finance.util.export.ExportFactory;
import com.finance.util.export.ImportUtil;
import com.finance.util.pager.Pagination;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: gly
 * @Date: Created in 2017-08-05
 */
@Controller
@RequestMapping("/rule/newrules")
public class NewRulesController extends BaseController {

    @Resource
    private INewRuleService newRuleService;
    @Resource
    private ISettlementRegionService settlementRegionService;
    @Resource
    private ISupplierService supplierService;
    @Resource
    private ICarrierService carrierService;
    @Resource
    private IRegionCodeService regionCodeService;

    @Resource
    private ISettingLogService settingLogService;

    @RequestMapping("/index.htm")
    public String index( HttpServletRequest request) {
        List<Region> regionCodeList = this.newRuleService.getFatherRegionList();
        List<Supplier> supplierList = this.newRuleService.getSupplierList();
        List<Carrier> carrierList = this.newRuleService.getCarrierList();
        request.setAttribute("regionList", regionCodeList);
        request.setAttribute("supplierList", supplierList);
        request.setAttribute("carrierList", carrierList);
        return "newrules/rulelist";
    }

    @RequestMapping("/list")
    public Result ruleList(String province,String city, String supplierCode, String carrierCode, Pagination pagination) {
        pagination = this.newRuleService.getRulePage(province, city, supplierCode, carrierCode, pagination);
        List<NewRuleList> newRuleLists = this.newRuleService.getRulesListPage(province, city, supplierCode, carrierCode, pagination);
        Map<String, Object> data = new HashMap<>();
        data.put("list", newRuleLists);
        data.put("pagination", pagination);

        return getSuccessResult(data);
    }


    @RequestMapping("/selectList")
    public Result selectList( ) {
        List<Region> regionCodeList = this.newRuleService.getFatherRegionList();
        List<Supplier> supplierList = this.newRuleService.getSupplierList();
        List<Carrier> carrierList = this.newRuleService.getCarrierList();
        Map<String, Object> data = new HashMap<>();
        data.put("regionList", regionCodeList);
        data.put("supplierList", supplierList);
        data.put("carrierList", carrierList);
        return getSuccessResult(data);
    }

    @RequestMapping("/cityRegionList")
    public Result cityRegionList( String provinceCode ) {
        List<Region> cityRegionList = this.newRuleService.getCityRegionList(provinceCode);
        Map<String, Object> data = new HashMap<>();
        data.put("cityRegionList", cityRegionList);
        return getSuccessResult(data);
    }

    @RequestMapping("/import/view")
    public String addRulePage() {
        return "newrules/ruleimport";
    }

    @RequestMapping("/add/view")
    public String addRulePage(HttpServletRequest request) {
        List<Region> regionCodeList = this.newRuleService.getFatherRegionList();
        List<Supplier> supplierList = this.newRuleService.getSupplierList();
        List<Carrier> carrierList = this.newRuleService.getCarrierList();
        request.setAttribute("regionList", regionCodeList);
        request.setAttribute("supplierList", supplierList);
        request.setAttribute("carrierList", carrierList);
        return "newrules/";
    }

    @RequestMapping("/edit/view")
    public String editRulePage(String ruleId, HttpServletRequest request) {
        List<Region> regionCodeList = this.newRuleService.getFatherRegionList();
        List<Supplier> supplierList = this.newRuleService.getSupplierList();
        List<Carrier> carrierList = this.newRuleService.getCarrierList();
        MasterRule masterRule = this.newRuleService.getMasterRule(ruleId);
        request.setAttribute("regionList", regionCodeList);
        request.setAttribute("supplierList", supplierList);
        request.setAttribute("carrierList", carrierList);
        request.setAttribute("masterRule", masterRule);
        if(masterRule != null){
            if(masterRule.getCalculateType() == CalculateTypeEnum.CALCULATE_BY_PIECE.getValue()){
                List<NewPieceRule> newPieceRules = this.newRuleService.getNewPieceRules(ruleId);
                request.setAttribute("pieceRules", newPieceRules);
            }else if(masterRule.getCalculateType() == CalculateTypeEnum.CALCULATE_BY_WEIGHT.getValue()){
                List<NewWeightRule> newWeightRules = this.newRuleService.getNewWeightRules(ruleId);
                request.setAttribute("weightRules", newWeightRules);
            }
        }
        return "newrules/";
    }

    @RequestMapping("/copy/view")
    public String copyRulePage(String ruleId, HttpServletRequest request) {
        List<Region> regionCodeList = this.newRuleService.getFatherRegionList();
        List<Supplier> supplierList = this.newRuleService.getSupplierList();
        List<Carrier> carrierList = this.newRuleService.getCarrierList();
        MasterRule masterRule = this.newRuleService.getMasterRule(ruleId);
        request.setAttribute("regionList", regionCodeList);
        request.setAttribute("supplierList", supplierList);
        request.setAttribute("carrierList", carrierList);
        request.setAttribute("masterRule", masterRule);
        if(masterRule != null){
            if(masterRule.getCalculateType() == CalculateTypeEnum.CALCULATE_BY_PIECE.getValue()){
                List< NewPieceRule > newPieceRules = this.newRuleService.getNewPieceRules(ruleId);
                request.setAttribute("pieceRules", newPieceRules);
            }else if(masterRule.getCalculateType() == CalculateTypeEnum.CALCULATE_BY_WEIGHT.getValue()){
                List< NewWeightRule > newWeightRules = this.newRuleService.getNewWeightRules(ruleId);
                request.setAttribute("weightRules", newWeightRules);
            }
        }
        return "newrules/ruleview";
    }

    /**
     * 新增规则
     *
     * @param newRulesReq
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result add(@Valid NewRulesReq newRulesReq) {
        User user = getAuthUser();
        if (user == null) {
            throw new BaseException(BaseConstants.ERR_UNKONW_USER);
        }
        String type = newRulesReq.getRuleType();
        if (!StringUtils.isNotBlank(type)) {
            throw new BaseException(BaseConstants.ERR_INVALID_PARAMETER);
        }
        if ("0".equals(type)) {


        }
        if ("1".equals(type)) {


        }
        return getSuccessResult("添加新规则成功");
    }

    /**
     * 修改规则
     *
     * @param newRulesReq
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Result update(@Valid NewRulesReq newRulesReq) {
        User user = getAuthUser();
        if (user == null) {
            throw new BaseException(BaseConstants.ERR_UNKONW_USER);
        }
        String type = newRulesReq.getRuleType();
        if (!StringUtils.isNotBlank(type)) {
            throw new BaseException(BaseConstants.ERR_INVALID_PARAMETER);
        }
        if ("0".equals(type)) {


        }
        if ("1".equals(type)) {


        }
        return getSuccessResult("修改规则成功");
    }


    /**
     * 按重计算规则Excel模板下载
     */
    @RequestMapping("/exporttemplate")
    public void export(HttpServletResponse response) {
        try {
            ExportBuilder builder = new ExportBuilder(NewWeightRuleImportTemplateBean.class, new NewWeightRuleParse());
            ExportFactory factory = ExportFactory.getExportFactory(builder);
            factory.setDataList(new ArrayList<NewWeightRule>()).outPut(response);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 按件计算规则Excel模板下载
     */
    @RequestMapping("/piece/exporttemplate")
    public void exportPiece(HttpServletResponse response) {
        try {
            ExportBuilder builder = new ExportBuilder (NewPieceRuleImportTemplateBean.class, new NewPieceRuleParse());
            ExportFactory factory = ExportFactory.getExportFactory(builder);
            factory.setDataList(new ArrayList<NewPieceRule>()).outPut(response);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 导入结果下载
     */
    @RequestMapping("/down")
    public void importData(String fileKey, HttpServletResponse response) {
        FileUtils.downFile(fileKey, response);
    }

    @RequestMapping("/import/process")
    @ResponseBody
    public Object importRuleProcess(String type){
        Subject subject = SecurityUtils.getSubject();
        return subject.getSession().getAttribute(type);
    }

    /**
     * 按重导入
     */
    @RequestMapping("/import")
    public Result importData(@RequestParam("file") CommonsMultipartFile[] multipartFile) {
        User user = getAuthUser();
        if (user == null) {
            throw new BaseException(BaseConstants.ERR_UNKONW_USER);
        }
        Session session = SecurityUtils.getSubject().getSession();
        InputStream in = null;
        List<NewWeightRule> successList = new ArrayList<NewWeightRule>();
        List<NewWeightRule> errList = new ArrayList<NewWeightRule>();
        List<String> errMsg = new ArrayList<String>();
        DecimalFormat df = new DecimalFormat("#.##");
        int nums = 0;
        int totalNums = 0;
        int flag = 0;
        long version=0;
        try {
            in = multipartFile[0].getInputStream();
            session.setAttribute("weightRuleProcess", "\"{'msg':'解析按重计算规则...','val':30}\"");
            Thread.sleep(500);
            List<NewWeightRuleImportTemplateBean> list = ImportUtil.getImportFactory(in).outResult(NewWeightRuleImportTemplateBean.class);
            session.setAttribute("pieceRuleProcess", "\"{'msg':'解析按重计算规则...','val':100}\"");
            Thread.sleep(500);
            session.setAttribute("weightRuleProcess", "\"{'msg':'验证按重计算规则是否有重复..','val':60}\"");
            Thread.sleep(500);
            totalNums = list.size();
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    NewWeightRuleImportTemplateBean item = list.get(i);
                    for (int j = i+1; j < list.size(); j++) {
                        if (item.equals(list.get(j))) {
                            errMsg.add("规则重复");
                            NewWeightRuleExcel newWeightRule = item.toNewWeightRuleExcel();
                            errList.add(newWeightRule);
                            break;
                        }
                    }
                }
                nums = errList.size();
            }
            session.setAttribute("pieceRuleProcess", "\"{'msg':'验证按重计算规则是否有重复...','val':100}\"");
            Thread.sleep(500);
            if (errList.size() == 0 && list != null && list.size() > 0) {
                flag = 1;
                int i =0;
                int size = list.size();
                for (NewWeightRuleImportTemplateBean bean : list) {
                    NewWeightRuleImportReq form = new NewWeightRuleImportReq(bean,supplierService,carrierService,regionCodeService);
                    List<String> msgList = validate(form);
                    if (null == msgList || msgList.size() == 0) {
                        NewWeightRule newWeightRules = new NewWeightRule();
                        BeanUtils.copyProperties(newWeightRules,form);
                        newWeightRules.setFromProvince(form.getFromProvince());
                        newWeightRules.setFromCity(form.getFromCity());
                        newWeightRules.setSettlementType(form.getSettlementType());
                        newWeightRules.setToCity(form.getToCity());
                        successList.add(newWeightRules);
                    } else{
                        NewWeightRuleExcel newWeightRule =  bean.toNewWeightRuleExcel();
                        StringBuffer msgStr = new StringBuffer();
                        for (String msg : msgList) {
                            msgStr.append(msg + "||");
                        }
                        msgStr.replace(msgStr.lastIndexOf("||"), msgStr.length(), "");
                        errMsg.add(msgStr.toString());
                        errList.add(newWeightRule);
                    }
                    session.setAttribute("weightRuleProcess", String.format("\"{'msg':'验证按重计算规则完整性，第%d条 %s','val':%s}\"",++i,(i%2==0 ? "..." : ".."),df.format(((i)*1.0/ size * 100))));
                }
                nums = errList.size();
            }
            if(errList.size() == 0 && successList != null && successList.size()>0){
                flag = 2;
                nums = list.size();
                session.setAttribute("weightRuleProcess", "\"{'msg':'开始导入按重计算规则...','val':20}\"");
                List<Map<String,Object>> ruleList = ConvertWeightRule(successList);
                session.setAttribute("weightRuleProcess", "\"{'msg':'开始导入按重计算规则...','val':60}\"");
                Thread.sleep(500);
                if (ruleList.size() >0 ){
                    session.setAttribute("pieceRuleProcess","\"{'msg':'导入按重计算规则...','val':70}\"");
                    version =newRuleService.saveNewWeightRule(ruleList,user);
                }
            }
        } catch (Exception e) {
            return getFailResult(BaseConstants.ERR_UNKOWN, e.getMessage());
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
        session.setAttribute("weightRuleProcess", "end");
        String fileKey = null;
        if (errList != null && errList.size() > 0) {
            File file = null;
            try {
                file = new File(getRealPath("") + System.currentTimeMillis() + BaseConstants.DEFAULT_EXPORT_FILE_SUFFIX);
                ExportFactory.getExportFactory(new ExportBuilder(NewWeightRuleImportTemplateBean.class, new NewWeightRuleParse()))
                       .setErrMsgList(errMsg).setDataList(errList).outPut(file);
                fileKey = FileUtils.uploadFile("import/newrules/", file.getName(), file);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            } finally {
                if (file != null) { file.delete(); }
            }
        }
        String desc ="导入按重计算规则 总数："+totalNums+"条，"+(flag == 0 ? ("规则重复："+nums+"条，导入失败"): flag ==1 ? ("验证失败："+nums+"，导入失败") :"成功"+nums+"条");
        settingLogService.addLog(user,TargetEnum.RULE_INFO,desc+(version > 0 ? " 备份版本号"+version : ""));
        Map<String, String> returnMap = new HashMap<String, String>(4);
        returnMap.put("fileKey", fileKey);
        returnMap.put("desc", desc);
        returnMap.put("totalNums", String.valueOf(totalNums));
        returnMap.put("flag", String.valueOf(flag));
        return getSuccessResult(returnMap);
    }

    /**
     * 按件导入
     */
    @RequestMapping("/piece/import")
    public Result importPieceData(@RequestParam("file") CommonsMultipartFile[] multipartFile) {
        String desc ="";
        User user = getAuthUser();
        if (user == null) {
            throw new BaseException(BaseConstants.ERR_UNKONW_USER);
        }
        Session session = SecurityUtils.getSubject().getSession();
        InputStream in = null;
        List<NewPieceRule> successList = new ArrayList<NewPieceRule>();
        List<NewPieceRule> errList = new ArrayList<NewPieceRule>();
        List<String> errMsg = new ArrayList<String>();
        DecimalFormat df = new DecimalFormat("#.##");
        int nums = 0;
        int totalNums = 0;
        int flag = 0;
        long version = 0;
        try {
            in = multipartFile[0].getInputStream();
            session.setAttribute("pieceRuleProcess", "\"{'msg':'解析按件计算规则...','val':30}\"");
            Thread.sleep(500);
            List<NewPieceRuleImportTemplateBean> list = ImportUtil.getImportFactory(in).outResult(NewPieceRuleImportTemplateBean.class);
            session.setAttribute("pieceRuleProcess", "\"{'msg':'解析按件计算规则...','val':100}\"");
            Thread.sleep(500);
            session.setAttribute("pieceRuleProcess", "\"{'msg':'验证按件计算规则是否有重复...','val':10}\"");
            Thread.sleep(500);
            totalNums = list.size();
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    NewPieceRuleImportTemplateBean item = list.get(i);
                    for (int j = i+1; j < list.size(); j++) {
                        if (item.equals(list.get(j))) {
                            errMsg.add("规则重复");
                            NewPieceRuleExcel newPieceRule = item.toNewPieceRuleExcel();
                            errList.add(newPieceRule);
                            break;
                        }
                    }
                }
                nums = errList.size();
            }
            session.setAttribute("pieceRuleProcess", "\"{'msg':'验证按件计算规则是否有重复...','val':100}\"");
            Thread.sleep(500);
            if (errList.size() == 0 && list != null && list.size() > 0) {
                flag = 1;
                int i =0;
                int size = list.size();
                for (NewPieceRuleImportTemplateBean bean : list) {
                    NewPieceRuleImportReq form = new NewPieceRuleImportReq(bean,supplierService,carrierService,regionCodeService);
                    List<String> msgList = validate(form);
                    if (null == msgList || msgList.size() == 0) {
                        NewPieceRule newPieceRules = new NewPieceRule();
                        BeanUtils.copyProperties(newPieceRules,form);
                        newPieceRules.setFromProvince(form.getFromProvince());
                        newPieceRules.setFromCity(form.getFromCity());
                        newPieceRules.setSettlementType(form.getSettlementType());
                        newPieceRules.setToCity(form.getToCity());
                        successList.add(newPieceRules);
                    } else{
                        NewPieceRuleExcel newPieceRule = bean.toNewPieceRuleExcel();
                        StringBuffer msgStr = new StringBuffer();
                        for (String msg : msgList) {
                            msgStr.append(msg + "||");
                        }
                        msgStr.replace(msgStr.lastIndexOf("||"), msgStr.length(), "");
                        errMsg.add(msgStr.toString());
                        errList.add(newPieceRule);
                    }
                    session.setAttribute("pieceRuleProcess", String.format("\"{'msg':'验证按件计算规则完整性，第%d条 %s','val':%s}\"",++i,(i%2==0 ? "..." : ".."),df.format(((i)*1.0/ size * 100))));
                }
                nums = errList.size();
            }
            if(errList.size() == 0 && successList != null && successList.size() > 0){
                flag = 2;
                nums = list.size();
                session.setAttribute("pieceRuleProcess", "\"{'msg':'开始准备导入按件计算规则...','val':20}\"");
                List<Map<String,Object>> ruleList = ConvertPieceRule(successList);
                session.setAttribute("pieceRuleProcess", "\"{'msg':'开始准备导入按件计算规则...','val':100}\"");
                Thread.sleep(500);
                int size = ruleList.size();
                if (size >0 ) {
                    session.setAttribute("pieceRuleProcess","\"{'msg':'导入按件计算规则...','val':70}\"");
                    version = newRuleService.saveNewPieceRule(ruleList,user);
                }
            }
        } catch (Exception e) {
            return getFailResult(BaseConstants.ERR_UNKOWN, e.getMessage());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
        session.setAttribute("pieceRuleProcess", "end");
        String fileKey = null;
        if (errList != null && errList.size() > 0) {
            File file = null;
            try {
                file = new File(getRealPath("") +System.currentTimeMillis() + BaseConstants.DEFAULT_EXPORT_FILE_SUFFIX);
                ExportFactory.getExportFactory(new ExportBuilder (NewPieceRuleImportTemplateBean.class,  new NewPieceRuleParse()))
                      .setErrMsgList(errMsg).setDataList(errList).outPut(file);
                fileKey = FileUtils.uploadFile("import/newrules/", file.getName(), file);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            } finally {
                if (file != null) {file.delete();}
            }
        }
        desc ="导入按件计算规则 总数："+totalNums+"条，"+(flag == 0 ? ("规则重复："+nums+"条，导入失败"): flag ==1 ? ("验证失败："+nums+"条，导入失败") :"成功"+nums+"条");
        settingLogService.addLog(user,TargetEnum.RULE_INFO,desc+(version >0 ? " 备份版本号"+version : ""));
        Map<String, String> returnMap = new HashMap<String, String>(4);
        returnMap.put("fileKey", fileKey);
        returnMap.put("desc",desc);
        returnMap.put("totalNums", String.valueOf(totalNums));
        returnMap.put("flag", String.valueOf(flag));
        return getSuccessResult(returnMap);
    }

    private List<Map<String,Object>> ConvertWeightRule(List<NewWeightRule> newWeightRuleList){
        List<MasterRule> masterRuleList = new ArrayList<MasterRule>();
        Date  date = new Date();
        for (NewWeightRule newWeightRule : newWeightRuleList){
            String supplierCode =newWeightRule.getSupplierCode();
            String carrierCode =newWeightRule.getCarrierCode();
            String toProvince =String.valueOf(newWeightRule.getToProvince());
            if (!isContains(masterRuleList,supplierCode,carrierCode,toProvince)){
                MasterRule masterRule = new MasterRule();
                masterRule.setSupplierCode(newWeightRule.getSupplierCode());
                masterRule.setCarrierCode(newWeightRule.getCarrierCode());
                masterRule.setToProvince(String.valueOf(newWeightRule.getToProvince()));
                masterRule.setUpdateTime(date);
                masterRule.setSettlementTypeFlag(Integer.valueOf(null == newWeightRule.getSettlementType()?0:1));
                masterRule.setSettlementRegionFlag(Integer.valueOf(null == newWeightRule.getRegionId()?0:1));
                masterRule.setFromProvinceFlag(Integer.valueOf(null == newWeightRule.getFromProvince()?0:1));
                masterRule.setFromCityFlag(Integer.valueOf(null == newWeightRule.getFromCity()?0:1));
                masterRule.setCodFlag(Integer.valueOf(null == newWeightRule.getCod()?0:1));
                masterRule.setDirectionFlag(Integer.valueOf(null == newWeightRule.getDirection()?0:1));
                masterRule.setExpressScheduleTypeFlag(Integer.valueOf(null == newWeightRule.getExpressScheduleType()?0:1));
                masterRule.setTemperatureTypeFlag(Integer.valueOf(null == newWeightRule.getTemperature()?0:1));
                masterRule.setCainiaoFlag(Integer.valueOf(null == newWeightRule.getCainiao()?0:1));
                masterRule.setCalculateType(Integer.valueOf(1));
                masterRule.setIsCombined(newWeightRule.getIsCombined());
                masterRuleList.add(masterRule);
            }
        }
        List<Map<String,Object>> ruleList = new ArrayList<Map<String,Object>>(masterRuleList.size());
        if (masterRuleList.size()>0){
            for(MasterRule masterRule: masterRuleList){
                List<NewWeightRule> list =getNewWeightRuleList(masterRule,newWeightRuleList);
                Map<String,Object> rule= new HashMap<String,Object>(2);
                rule.put("masterRule",masterRule);
                rule.put("newWeightRuleList",list);
                ruleList.add(rule);
            }
        }
        return ruleList;
    }

    private List<NewWeightRule> getNewWeightRuleList(MasterRule masterRule,List<NewWeightRule> newWeightRuleList){
        List<NewWeightRule>  list = new  ArrayList<NewWeightRule>();
        String supplierCode =masterRule.getSupplierCode();
        String carrierCode =masterRule.getCarrierCode();
        String toProvince =String.valueOf(masterRule.getToProvince());
        for(NewWeightRule newWeightRule: newWeightRuleList){
            if(supplierCode.equals(newWeightRule.getSupplierCode())
                    && carrierCode.equals( newWeightRule.getCarrierCode())
                    && toProvince.equals(String.valueOf(newWeightRule.getToProvince()))){
                list.add(newWeightRule);
            }
        }
        return list;
    }

    private List<Map<String,Object>> ConvertPieceRule(List<NewPieceRule> newPieceRuleList){
        List<MasterRule> masterRuleList = new ArrayList<MasterRule>();
        Date  date = new Date();
        for (NewPieceRule newPieceRule : newPieceRuleList){
            String supplierCode =newPieceRule.getSupplierCode();
            //String carrierCode =newPieceRule.getCarrierCode();
            String carrierCode =newPieceRule.getPatternRule();
            String toProvince =String.valueOf(newPieceRule.getToProvince());
            if (!isContains(masterRuleList,supplierCode,carrierCode,toProvince)){
                MasterRule masterRule = new MasterRule();
                masterRule.setSupplierCode(newPieceRule.getSupplierCode());
                //masterRule.setCarrierCode(newPieceRule.getCarrierCode());
                masterRule.setCarrierCode(newPieceRule.getPatternRule());
                masterRule.setToProvince(String.valueOf(newPieceRule.getToProvince()));
                masterRule.setUpdateTime(date);
                masterRule.setSettlementTypeFlag(Integer.valueOf(null == newPieceRule.getSettlementType()?0:1));
                masterRule.setSettlementRegionFlag(Integer.valueOf(null == newPieceRule.getRegionId()?0:1));
                masterRule.setFromProvinceFlag(Integer.valueOf(null == newPieceRule.getFromProvince()?0:1));
                masterRule.setFromCityFlag(Integer.valueOf(null == newPieceRule.getFromCity()?0:1));
                masterRule.setCodFlag(Integer.valueOf(null == newPieceRule.getCodMajor()?0:1));
                masterRule.setDirectionFlag(Integer.valueOf(null == newPieceRule.getDirectionMajor()?0:1));
                masterRule.setExpressScheduleTypeFlag(Integer.valueOf(null == newPieceRule.getExpressScheduleTypeMajor()?0:1));
                masterRule.setTemperatureTypeFlag(Integer.valueOf(null == newPieceRule.getTemperatureMajor()?0:1));
                masterRule.setCainiaoFlag(Integer.valueOf(null == newPieceRule.getCainiaoMajor()?0:1));
                masterRule.setCalculateType(Integer.valueOf(0));
                masterRule.setIsCombined(null);
                masterRuleList.add(masterRule);
            }
        }
        List<Map<String,Object>> ruleList = new ArrayList<Map<String,Object>>(masterRuleList.size());
        if (masterRuleList.size()>0){
            for(MasterRule masterRule: masterRuleList){
                List<NewPieceRule> list =getNewPieceRuleList(masterRule,newPieceRuleList);
                Map<String,Object> rule= new HashMap<String,Object>(2);
                rule.put("masterRule",masterRule);
                rule.put("newPieceRuleList",list);
                ruleList.add(rule);
            }
        }
        return ruleList;
    }

    private List<NewPieceRule> getNewPieceRuleList(MasterRule masterRule,List<NewPieceRule> newPieceRuleList){
        List<NewPieceRule>  list = new  ArrayList<NewPieceRule>();
        String supplierCode =masterRule.getSupplierCode();
        String carrierCode = masterRule.getCarrierCode();
        String toProvince =String.valueOf(masterRule.getToProvince());
        for(NewPieceRule newPieceRule: newPieceRuleList){
            if(supplierCode.equals(newPieceRule.getSupplierCode())
                    //&& carrierCode.equals( newPieceRule.getCarrierCode())
                    && carrierCode.equals( newPieceRule.getPatternRule())
                    && toProvince.equals(newPieceRule.getToProvince())){
                list.add(newPieceRule);
            }
        }
        return list;
    }

    private boolean isContains(List<MasterRule> masterRuleList, String supplierCode, String carrierCode, String toProvince){
        for(MasterRule masterRule: masterRuleList){
            if(supplierCode.equals(masterRule.getSupplierCode())
                    && carrierCode.equals( masterRule.getCarrierCode())
                    && toProvince.equals(masterRule.getToProvince())){
                return true;
            }
        }
        return false;
    }

}




